import { ArrowLeft, Volume, PlayCircle, PauseCircle } from '@react-vant/icons'
import { useEffect, useRef, useState } from 'react'
import { getAnimalList } from '../../components/getAnimalList'
import LLMChat from '../../components/LLMChat'
import { Button } from 'react-vant';
import { useNavigate } from 'react-router'
import shark from '../../assets/shark.png'
import panda from '../../assets/panda.png'
import pig from '../../assets/pig.png'
import pig1 from '../../assets/pig1.png'
import proud from '../../assets/proud.png'
export default function characters() {
  const navigate = useNavigate()
  const [content, setContent] = useState(0)//当前显示的汉字在数组内的下标
  const [Hanzi, setHanzi] = useState('')
  const [isLoading, setIsLoading] = useState(false)//ai问题的加载状态
  const [isHanziPlaying, setIsHanziPlaying] = useState(false)//是否正在播放汉字
  const [isStoryPlaying, setIsStoryPlaying] = useState(false)//是否正在播放故事
  const [isImageLoading, setIsImageLoading] = useState(false)//是否正在加载图片
  const [ImageURL, setImageURL] = useState('')
  const [HanziAudio, setHanziAudio] = useState('')
  const [StoryAudio, setStoryAudio] = useState('')
  const [StoryContent, setStoryContent] = useState('')
  const HanziAudioRef = useRef<HTMLAudioElement>(null)
  const StoryAudioRef = useRef<HTMLAudioElement>(null)
  const [WordList, setWordList] = useState<{ word: string, explanation: string }[]>([])//组词的汉字数组
  const patToken = import.meta.env.VITE_PAT_TOKEN
  const uploadUrl = 'https://api.coze.cn/v1/files/upload'//上传和鉴权地址
  const workflowUrl = 'https://api.coze.cn/v1/workflow/run'//工作流地址
  const workflow_id = '7541983453770186790'//工作流id
  // 修改 generate 函数接受参数
  const generate = async (currentHanzi: string) => {
    stopAllAudio()
    setIsImageLoading(true)
    try {
      const res = await fetch(workflowUrl, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${patToken}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          workflow_id: workflow_id,
          parameters: {
            Hanzi: currentHanzi  // 使用传入的参数
          }
        })
      })
      const ret = await res.json()
      console.log(ret);
      const data = JSON.parse(ret.data)
      setImageURL(data.ImageURL)
      setHanziAudio(data.HanziAudio)
      setStoryAudio(data.StoryAudio)
      setStoryContent(data.StoryContent)
    } catch (err) {
      console.error('获取数据失败:', err)
    } finally {
      setIsImageLoading(false)
    }
  }
  //停止所有音频播放
  function stopAllAudio() {
    if (HanziAudioRef.current) {
      HanziAudioRef.current.pause()
      HanziAudioRef.current.currentTime = 0
    }
    if (StoryAudioRef.current) {
      StoryAudioRef.current.pause()
      StoryAudioRef.current.currentTime = 0
    }
    setIsHanziPlaying(false)
    setIsStoryPlaying(false)
  }
  function toggleHanziAudio() {
    if (!HanziAudioRef.current || !HanziAudio) return
    if (isStoryPlaying && StoryAudioRef.current) {
      StoryAudioRef.current.pause()
      StoryAudioRef.current.currentTime = 0
      setIsStoryPlaying(false)
    }
    if (isHanziPlaying) {
      HanziAudioRef.current.pause()
      HanziAudioRef.current.currentTime = 0
    } else {
      HanziAudioRef.current.play().catch(err => console.error('播放失败:', err))
    }
    setIsHanziPlaying(!isHanziPlaying)
  }
  function toggleStoryAudio() {
    if (!StoryAudioRef.current || !StoryAudio) return
    if (isHanziPlaying && HanziAudioRef.current) {
      HanziAudioRef.current.pause()
      HanziAudioRef.current.currentTime = 0
      setIsHanziPlaying(false)
    }
    if (isStoryPlaying) {
      StoryAudioRef.current.pause()
      StoryAudioRef.current.currentTime = 0
    } else {
      StoryAudioRef.current.play().catch(err => console.error('播放失败:', err))
    }
    setIsStoryPlaying(!isStoryPlaying)
  }
  function refreshContent() {
    setIsImageLoading(true)
    const animal = getAnimalList(content)
    setHanzi(animal)
    generate(animal) // 直接传递最新的animal值
    // 更新计数器
    setContent(prev => prev < 19 ? prev + 1 : 0)
  }
  useEffect(() => {
    const hanziAudio = HanziAudioRef.current;
    const storyAudio = StoryAudioRef.current;
    const handleHanziEnded = () => setIsHanziPlaying(false);
    const handleStoryEnded = () => setIsStoryPlaying(false);
    if (hanziAudio) {
      hanziAudio.addEventListener('ended', handleHanziEnded);
    }
    if (storyAudio) {
      storyAudio.addEventListener('ended', handleStoryEnded);
    }
    return () => {
      if (hanziAudio) {
        hanziAudio.removeEventListener('ended', handleHanziEnded);
      }
      if (storyAudio) {
        storyAudio.removeEventListener('ended', handleStoryEnded);
      }
    };
  }, [])
  // 在 useEffect 中调用
  useEffect(() => {
    refreshContent()
  }, [])
  return (
    <div className="flex flex-col items-center justify-center w-dvw h-dvh">
      {/* header */}
      <div className=' relative flex flex-row items-center justify-between h-8 w-full p-2 bg-orange-300'>
        <div className='absolute overflow-hidden w-10 right-1 top-1/2 -translate-y-1/2'>
          <img src={panda} alt="" />
        </div>
        <div className='bg-yellow-50 w-4 h-4 flex items-center justify-center rounded-md '>
          <div className='text-orange-300 text-xs'
            onClick={() => {
              navigate('/home')
            }}
          >
            <ArrowLeft />
          </div>
        </div>
        <div className='text-xs text-neutral-100 mr-10 font-bold'>
          神奇的汉字
        </div>
      </div>
      {/* body */}
      <div className=' relative flex-1 flex flex-col items-center justify-between bg-yellow-50 w-full'>
        {/* 汉字 */}
        <div className='  flex items-center justify-between w-[80%]'>
          <div className='absolute w-14 overflow-hidden top-1  right-1 z-1'>
            <img src={pig} alt="" />
          </div>
          <div className='absolute w-10 overflow-hidden top-16  right-4 z-11'>
            <img src={proud} alt="" />
          </div>
          <div className='absolute w-7 overflow-hidden top-32  right-5 z-11'>
            <img src={shark} alt="" />
          </div>
          <div className='flex items-center justify-center mt-2 rounded-xl  w-[4.5rem] h-[4.5rem] bg-orange-300 '>
            <div className='text-5xl font-bold text-gray-700'>
              {Hanzi}
            </div>
          </div>
          <div className='font-bold z-10'
            style={{
              '--rv-button-danger-background-color': '#F7AE25',
              '--rv-button-danger-border-color': '#F7AE25'
            } as React.CSSProperties}
            onClick={() => {
              refreshContent()
            }}
          >
            <Button type='danger' round>下一题</Button>
          </div>
        </div>
        {/* 图片发音以及故事 */}
        <div className='flex items-center justify-between h-24 mt-2 w-full px-2'>
          <div className='w-20 rounded-lg overflow-hidden'>
            {
              isImageLoading ? (
                <div className='w-full h-20 bg-gray-200 flex items-center justify-center'>
                  图片正在路上，请稍后
                </div>
              ) : ImageURL ? (
                <img src={ImageURL} alt="" />
              ) : (
                <div className='w-full h-20 bg-gray-200 flex items-center justify-center'>
                  点击下一题获取图片
                </div>
              )
            }
          </div>
          <div className='flex flex-col items-center justify-between h-full py-3'>
            <div className=' w-14 h-7  bg-orange-300 rounded-xl flex justify-center items-center'
              onClick={() => {
                toggleHanziAudio()
              }}
            >
              <div>
                {isHanziPlaying ? <PauseCircle className='w-3 h-3 text-white' /> : <PlayCircle className='w-3 h-3 text-white' />}
              </div>
              <div className='text-white text-[27px] font-bold'>
                听读音
              </div>
              <div className=' hidden'>
                <audio src={HanziAudio} controls ref={HanziAudioRef}></audio>
              </div>
            </div>
            <div className='w-14 h-7  bg-[#786634] rounded-xl flex justify-center items-center'
              onClick={() => {
                toggleStoryAudio()
              }}
            >
              <div>
                {isStoryPlaying ? <PauseCircle className='w-3 h-3 text-white' /> : <PlayCircle className='w-3 h-3 text-white' />}
              </div>
              <div className='text-white text-[15px] font-bold'>
                听起源故事
              </div>
              <div className=' hidden'>
                <audio src={StoryAudio} controls ref={StoryAudioRef}></audio>
              </div>
            </div>
          </div>
        </div>
        {/* ai */}
        <div className='flex-1 flex flex-col items-center justify-between w-full mb-2'>
          <div className='w-[90%] h-full text-[20px] bg-gray-200 rounded-lg flex flex-col items-center justify-between'>
            <div className=' flex justify-between items-center mt-1 h-2 w-full px-2'>
              <div className='text-[17px]'>
                你可以用{Hanzi}组成哪些词语？
              </div>
              <div className='text-[17px]'
                style={{
                  '--rv-button-danger-background-color': '#F7AE25',
                  '--rv-button-danger-border-color': '#F7AE25'
                } as React.CSSProperties}
                onClick={async () => {
                  setIsLoading(true); // 设置加载状态为true
                  try {
                    const data = await LLMChat(Hanzi);
                    setWordList(data);
                  } catch (error) {
                    console.error('获取数据失败:', error);
                    // 可以在这里添加错误提示
                  } finally {
                    setIsLoading(false); // 请求完成后，无论成功失败都设置加载状态为false
                  }
                }}
              >
                <Button type='danger' size='small' round={true}>问问ai</Button>
              </div>
            </div>
            <div className='h-[100px] w-full mt-1 px-2 flex flex-col items-center overflow-y-auto'>
              {isLoading ? (
                <div className='text-center text-[17px] text-neutral-700'>内容正在生成中，请稍后...</div>
              ) : Array.isArray(WordList) && WordList.length > 0 ? (
                WordList.map((item: { word: string, explanation: string }, index) => {
                  return (
                    <div key={index} className='w-full py-1 border-b border-gray-200'>
                      <span className='font-bold'>{item.word}:</span>{item.explanation}
                    </div>
                  )
                })
              ) : (
                <div className='text-center text-[17px]'>请点击按钮</div>
              )}
            </div>
          </div>
        </div>
      </div>

    </div>
  )
}
